package com.xdap.common.dao;

import com.definesys.mpaas.query.MpaasQueryFactory;
import com.xdap.api.moudle.formconfig.pojo.XdapFormConfig;
import com.xdap.common.config.MongoDatasourceContainer;
import com.xdap.common.entity.XdapSessionEntity;
import com.xdap.common.session.XdapSession;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
@RequiredArgsConstructor
public class InitFormDao {
    private final MongoDatasourceContainer mongoDatasourceContainer;
    private final MpaasQueryFactory mqf;
    @Value("${apaas.single.tenantId}")
    private String tenantSchema;

    public XdapFormConfig getXdapFormConfig(String formId) {
        XdapSession.setXdapSession(XdapSessionEntity.builder()
                .mongoDatasource(this.mongoDatasourceContainer
                        .findMongoDatasource("mongoxdap_app_" + tenantSchema))
                .mysqlDatasource("xdap_app_" + tenantSchema).tenantId(tenantSchema).build());
        XdapFormConfig process = mqf.buildQuery(XdapSession.mongoDatasource(), "mongodb")
                .eq("_id", new ObjectId(formId))
                .table("xdap_form_config").doQueryFirst(XdapFormConfig.class);
        XdapSession.remove();
        return process;
    }

    public List<XdapFormConfig> getAllEnableXdapFormConfig() {
        XdapSession.setXdapSession(XdapSessionEntity.builder()
                .mongoDatasource(this.mongoDatasourceContainer
                        .findMongoDatasource("mongoxdap_app_" + tenantSchema))
                .mysqlDatasource("xdap_app_" + tenantSchema).tenantId(tenantSchema).build());
        List<XdapFormConfig> formList = mqf.buildQuery(XdapSession.mongoDatasource(), "mongodb")
                .eq("status", "ENABLE")
                .table("xdap_form_config").doQuery(XdapFormConfig.class);
        XdapSession.remove();
        return formList;
    }

}
